#include <stdio.h>
#include <math.h>

#define PI 3.14159265358979323846

void writeDXFHeader(FILE *file) {
    fprintf(file, "0\nSECTION\n2\nHEADER\n0\nENDSEC\n");
    fprintf(file, "0\nSECTION\n2\nTABLES\n0\nENDSEC\n");
    fprintf(file, "0\nSECTION\n2\nBLOCKS\n0\nENDSEC\n");
    fprintf(file, "0\nSECTION\n2\nENTITIES\n");
}

void writeDXFFooter(FILE *file) {
    fprintf(file, "0\nENDSEC\n0\nEOF\n");
}

void writeCircle(FILE *file, double x, double y, double r) {
    fprintf(file, "0\nCIRCLE\n8\n0\n10\n%.4f\n20\n%.4f\n30\n0.0\n40\n%.4f\n", x, y, r);
}

void writeLine(FILE *file, double x1, double y1, double x2, double y2) {
    fprintf(file, "0\nLINE\n8\n0\n10\n%.4f\n20\n%.4f\n30\n0.0\n11\n%.4f\n21\n%.4f\n31\n0.0\n",
            x1, y1, x2, y2);
}

void writeGearDXF(const char *filename, double m, int z) {
    FILE *file = fopen(filename, "w");
    if (!file) {
        printf("无法创建 DXF 文件\n");
        return;
    }

    // 计算齿轮参数
    double d = m * z;          // 分度圆直径
    double ha = (z + 2) * m;   // 齿顶圆直径
    double hf = (z - 2.5) * m; // 齿根圆直径
    double db = d * cos(PI / 9.0); // 基圆直径

    // DXF 头部
    writeDXFHeader(file);

    // 画齿轮关键圆
    writeCircle(file, 0, 0, d / 2);   // 分度圆
    writeCircle(file, 0, 0, ha / 2);  // 齿顶圆
    writeCircle(file, 0, 0, hf / 2);  // 齿根圆
    writeCircle(file, 0, 0, db / 2);  // 基圆

    // 生成渐开线齿形
    for (int i = 0; i < z; i++) {
        double theta = 2 * PI * i / z; // 每个齿的角度
        double x1 = (d / 2) * cos(theta);
        double y1 = (d / 2) * sin(theta);
        double x2 = (ha / 2) * cos(theta);
        double y2 = (ha / 2) * sin(theta);
        writeLine(file, x1, y1, x2, y2); // 齿顶连接线
    }

    // DXF 结束
    writeDXFFooter(file);
    fclose(file);

    printf("DXF 文件 %s 生成成功！\n", filename);
}

int main() {
    double m;
    int z;

    printf("请输入模数 m（单位：mm）：");
    scanf("%lf", &m);
    printf("请输入齿数 z：");
    scanf("%d", &z);

    writeGearDXF("gear.dxf", m, z);
    printf("DXF 文件 gear.dxf 生成成功，可以导入 SolidWorks ！\n");
    return 0;
}
